/*
 * Copyright 2010 Electronic Business Systems Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gr.ebs.gssdroid.widget;

import gr.ebs.gssdroid.http.GssHttpCommands;
import gr.ebs.gssdroid.http.GssHttpException;
import gr.ebs.gssdroid.http.SystemErrorException;
import gr.ebs.gssdroid.resource.GroupResource;
import gr.ebs.gssdroid.resource.UserResource;
import gr.ebs.gssdroid.resource.UserSearchResource;
import gr.ebs.gssdroid.util.UserDetails;

import java.net.URLEncoder;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.CursorAdapter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class UserAdapter extends CursorAdapter implements Filterable {
	public static final String GROUP="GROUP";
	public static final String USER= "USER";
	 private TextView mName, mNumber;
    private Context context;
    UserDetails details;
    private int layout;
    List<String> groups;
    boolean userAdd;
    public UserAdapter (Context context, UserDetails details, List<String> groups, boolean userAdd) {
        super(context, new MatrixCursor(new String[] { "_id", "name", "type"}));
        this.context = context;
        this.details=details;
        this.groups=groups;
        this.userAdd=userAdd;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        final LinearLayout ret = new LinearLayout(context);
        final LayoutInflater inflater = LayoutInflater.from(context);
        mName = (TextView) inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
        mNumber = (TextView) inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
        ret.setOrientation(LinearLayout.VERTICAL);

        LinearLayout horizontal = new LinearLayout(context);
        horizontal.setOrientation(LinearLayout.HORIZONTAL);

        // you can even add images to each entry of your autocomplete fields
        // this example does it programmatically using JAVA, but the XML analog is very similar
        ImageView icon = new ImageView(context);

        
        String name = cursor.getString(1);
        String number = cursor.getString(2);

        mName.setText(name);
        mName.setTextColor(Color.BLACK);
        mNumber.setText(number);

        // setting the type specifics using JAVA
        mNumber.setTextSize(16);
        mNumber.setTextColor(Color.GRAY);
        // an example of how you can arrange your layouts programmatically
        // place the number and icon next to each other
        horizontal
                .addView(mNumber, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        horizontal.addView(icon, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        ret.addView(mName, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        ret.addView(horizontal, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        return ret;
    }
    
    @Override
    public String convertToString(Cursor cursor) {
        // this method dictates what is shown when the user clicks each entry in your autocomplete list
        // in my case i want the number data to be shown
       
        String number = cursor.getString(1);
        return number;
    }


    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        

        String name = cursor.getString(1);
        String number = cursor.getString(2);

        // notice views have already been inflated and layout has already been set so all you need to do is set the data
        ((TextView) ((LinearLayout) view).getChildAt(0)).setText(name);
        LinearLayout horizontal = (LinearLayout) ((LinearLayout) view).getChildAt(1);
        ((TextView) horizontal.getChildAt(0)).setText(number);
    }

    @Override
    public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
    	
    	MatrixCursor mCursor = new MatrixCursor(new String[] { "_id", "name", "type"});
    	if (constraint != null){
    		String query = String.valueOf(constraint);
    		
    		if(userAdd && query.length()>=3){
    			try {
					UserSearchResource res = new GssHttpCommands(details).getSearchUsers(details.getApiPath()+"users/"+URLEncoder.encode(query));
					long id =1l;
					for(UserResource u : res.getUsers()){
						mCursor.addRow(new Object[]{id, u.getUsername(),USER});
						id++;
					}
				} catch (SystemErrorException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (GssHttpException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    		else{
    			long id=1l;
    			for(String g :groups){
    				if(g.startsWith(query)){
    					mCursor.addRow(new Object[]{id, g,GROUP});
    					id++;
    				}
    			}
    			
    		}
    	}
        return mCursor;
    }
}
